package com.yanqu.road.server.push;

import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.language.LanguageType;
import com.yanqu.road.entity.logAnalysis.ItemChangeDetail;
import com.yanqu.road.entity.logAnalysis.RoleShopBuy;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.push.*;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.DataUploadInfoMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.CommonActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.queue.LogAnalysisPushQueue;
import com.yanqu.road.queue.PushQueue;
import com.yanqu.road.utils.TimeHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.List;

/**
 * @author duli
 * @version 1.0
 * @date 2020/9/7 16:39
 * @Description build推送数据
 */
public class PushMgr {
    private static final Logger log = LogManager.getLogger(PushMgr.class.getName());

    /**
     * build角色登陆 暂时废弃
     */
    public static void buildRoleLogin(GamePlayer player, long serverId, String serverName) {
        RoleLogin login = buildBaseRoleLogin(player, serverId, serverName);
        login.setEvent("rolelogin");
        PushQueue.add(login);
    }

    /**
     * build角色基础信息
     */
    private static RoleLogin buildBaseRoleLogin(GamePlayer player, long serverId, String serverName) {
        RoleLogin login = new RoleLogin();
        UserInfo userInfo = player.getUserInfo();
        login.setUser_id(userInfo.getOpenId());
        login.setRole_id(String.valueOf(userInfo.getUserId()));
        login.setRole_name(userInfo.getNickName());
        login.setRole_level(userInfo.getTitleId());
        login.setServer_id(String.valueOf(serverId));
        login.setServer_name(serverName);
        login.setClient_type(1);//todo
        login.setDevice_id(player.getDeviceId());
        login.setSource_id("");
        login.setEvent_ts((int) TimeHelper.getSysCurSeconds());
        return login;
    }

    /**
     * build支付
     */
    public static void buildPay(GamePlayer player, RechargeOrder rechargeOrder, ThirdPartyRechargeOrder thirdPartyRechargeOrder) {
        if (!DataUploadInfoMgr.isAllowUpload()) {
            return;
        }
        Pay pay = new Pay();
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        if (serverInfo == null) {
            log.error("Pay-serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
            return;
        }
        UserInfo userInfo = player.getUserInfo();
        pay.setUser_id(userInfo.getOpenId());
        pay.setRole_id(String.valueOf(userInfo.getUserId()));
        pay.setRole_name(userInfo.getNickName());
        pay.setRole_level(userInfo.getTitleId());
        pay.setServer_id(String.valueOf(serverInfo.getServerId()));
        pay.setServer_name(serverInfo.getServerName());
        pay.setEvent("pay");
        pay.setClient_type(0);//todo
        pay.setDevice_id(player.getDeviceId());
        pay.setSource_id(String.valueOf(serverInfo.getChannelId()));
        pay.setDevice_model("");//todo
        if (rechargeOrder == null) {
            //第三方支付
            pay.setPayment_type("第三方");
            pay.setTransaction_id(thirdPartyRechargeOrder.getPlatformOrderNo());
            pay.setCurrency_amount(String.valueOf(thirdPartyRechargeOrder.getAmount()));
            pay.setVirtual_coin_amount("");//todo 通过充值获得的游戏内货币的数量
            buildMallInfo(pay, thirdPartyRechargeOrder.getMallId());
        } else {
            pay.setPayment_type("游戏内");
            pay.setTransaction_id(rechargeOrder.getPlatformOrderNo());
            pay.setCurrency_amount(String.valueOf(rechargeOrder.getAmount()));
            pay.setVirtual_coin_amount("");//todo 通过充值获得的游戏内货币的数量
            buildMallInfo(pay, rechargeOrder.getMallId());
        }

        pay.setCurrency_type("");//todo
        pay.setEvent_ts((int) TimeHelper.getSysCurSeconds());
        PushQueue.add(pay);
    }


    /**
     * build支付流水中获取的道具信息
     */
    private static void buildMallInfo(Pay pay, int mallId) {
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        pay.setItem_id(mallInfo.getReward());
        pay.setItem_name("无");
        pay.setItem_num(0);
    }

    /**
     * build在线人数
     */
    public static void buildOnlineNum() {
        try {
            if (!DataUploadInfoMgr.isAllowUpload()) {
                return;
            }
            List<Long> gamePlayerList = GamePlayerMgr.getAllOnlinePlayerId();
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if (serverInfo == null) {
                log.error("OnlineNum-serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
                return;
            }
            OnlineNum onlineNum = new OnlineNum();
            onlineNum.setOnline_num(String.valueOf(gamePlayerList.size()));
            onlineNum.setServer_id(String.valueOf(serverInfo.getServerId()));
            onlineNum.setServer_name(serverInfo.getServerName());
            onlineNum.setSource_id(String.valueOf(serverInfo.getChannelId()));
            onlineNum.setEvent("onlinenum");
            onlineNum.setEvent_ts((int) TimeHelper.getSysCurSeconds());
            PushQueue.add(onlineNum);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    /**
     * build时长统计
     */
    public static void buildHeartbeat() {
        List<GamePlayer> gamePlayerList = GamePlayerMgr.getAllOnlinePlayer();
        if (CollectionUtils.isNotEmpty(gamePlayerList)) {
            for (GamePlayer player : gamePlayerList) {
                buildPushHeartbeat(player);
            }
        }

    }

    /**
     * build 游戏时长
     */
    public static void buildGameTime(GamePlayer player, int LogoutTimestamp) {
        try {
            if (!DataUploadInfoMgr.isAllowUpload()) {
                return;
            }
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if (serverInfo != null) {
                UserInfo userInfo = player.getUserInfo();
                GameTime time = new GameTime();
                time.setUser_id(userInfo.getOpenId());
                time.setRole_id(String.valueOf(userInfo.getUserId()));
                time.setRole_name(userInfo.getNickName());
                time.setServer_id(String.valueOf(serverInfo.getServerId()));
                time.setServer_name(serverInfo.getServerName());
                time.setClient_type(0);
                time.setDevice_id(player.getDeviceId());
                time.setSource_id(String.valueOf(serverInfo.getChannelId()));
                time.setEvent_ts((int) TimeHelper.getSysCurSeconds());
                time.setLogin_timestamp((int) userInfo.getLastLoginTime());
                time.setLogout_timestamp(LogoutTimestamp);
                time.setEvent("gametime");
                PushQueue.add(time);
            } else {
                log.error("GameTime serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * build资源变更
     */
    public static void buildItemChangeDetail(GamePlayer player, eItemChangeEnums.Type type, eItemChangeEnums.TypeItem typeItem, eLogMoneyType son, int goodsId, BigInteger value) {
        try {
            if (!DataUploadInfoMgr.isAllowUpload()) {
                return;
            }
            ItemChangeDetail itemChangeDetail = new ItemChangeDetail();
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if (serverInfo == null) {
                log.error("ItemChange-serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
                return;
            }
            UserInfo userInfo = player.getUserInfo();
            GoodsInfo goodInfo = GoodsMgr.getGoodsById(goodsId);
            if (goodInfo == null) {
                log.error("ItemChange-goods no fount, goodsId:{},count:{}", goodsId, value.toString());
                return;
            }
            itemChangeDetail.setAppId(Integer.parseInt(DataUploadInfoMgr.getDataUploadInfo().getAppId()));
            itemChangeDetail.setUserId(userInfo.getOpenId());
            itemChangeDetail.setRoleId(String.valueOf(userInfo.getUserId()));
            itemChangeDetail.setRoleName(userInfo.getNickName());
            itemChangeDetail.setServerId(String.valueOf(serverInfo.getServerId()));
            itemChangeDetail.setServerName(serverInfo.getServerName());
            itemChangeDetail.setType(type.getIntValue());
            itemChangeDetail.setTypeItem(typeItem.getIntValue());
            itemChangeDetail.setDeviceId(player.getDeviceId());
            int channelId = serverInfo.getChannelId();
            itemChangeDetail.setSourceId(String.valueOf(channelId));
            itemChangeDetail.setSourceName(eChannelType.forValue(channelId).getName());
            itemChangeDetail.setItemBigId(String.valueOf(goodInfo.getType()));
            itemChangeDetail.setTypeItemId(String.valueOf(son.getValue()));
            itemChangeDetail.setTypeItemName(son.getName());
            itemChangeDetail.setItemId(String.valueOf(goodsId));
            itemChangeDetail.setItemName(MultipleLanguageMgr.getContent(goodInfo.getGoodsName(), LanguageType.LANGUAGE_DEFAULT));
            itemChangeDetail.setItemNum(value.floatValue());
            itemChangeDetail.setEvent("change");
            itemChangeDetail.setCreatedTime((int) TimeHelper.getSysCurSeconds());
            LogAnalysisPushQueue.add(itemChangeDetail);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    /**
     * build商城购买
     */
    public static void buildShopBuy(GamePlayer player, BigInteger value, String desc) {
        try {
            if(StringUtils.isNullOrEmpty(desc)){
                return;
            }
            if(!desc.contains(":")){
                return;
            }
            if (!DataUploadInfoMgr.isAllowUpload()) {
                return;
            }
            RoleShopBuy roleShopBuy = new RoleShopBuy();
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if (serverInfo == null) {
                log.error("ShopBuy-serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
                return;
            }
            UserInfo userInfo = player.getUserInfo();
            String mallId = desc.substring(0, desc.indexOf(":"));
            String count = desc.substring(desc.indexOf(":") + 1, desc.length());
            MallInfo mallInfo = MallMgr.getMallInfoByMallId(Integer.parseInt(mallId));
            if (null == mallInfo) {
                mallInfo = CommonActivityMgr.getMallInfo(Integer.parseInt(mallId));
                if(null == mallInfo) {
                    log.error("ShopBuy-mallInfo no fount, mallId:{},count:{}", mallId, count);
                    return;
                }
            }
            roleShopBuy.setAppId(Integer.parseInt(DataUploadInfoMgr.getDataUploadInfo().getAppId()));
            roleShopBuy.setUserId(userInfo.getOpenId());
            roleShopBuy.setRoleId(String.valueOf(userInfo.getUserId()));
            roleShopBuy.setRoleName(userInfo.getNickName());
            roleShopBuy.setServerId(String.valueOf(serverInfo.getServerId()));
            roleShopBuy.setServerName(serverInfo.getServerName());
            roleShopBuy.setDeviceId(player.getDeviceId());
            int channelId = serverInfo.getChannelId();
            roleShopBuy.setSourceId(String.valueOf(channelId));
            roleShopBuy.setSourceName(eChannelType.forValue(channelId).getName());
            //商品总价值
            roleShopBuy.setConsumeNum(value.floatValue());
            roleShopBuy.setTypeItemId(String.valueOf(mallInfo.getShopType()));
            roleShopBuy.setTypeItemName(eShopType.forValue(mallInfo.getShopType()).getMallName());
            roleShopBuy.setItemId(mallId);
            roleShopBuy.setItemName(MultipleLanguageMgr.getContent(mallInfo.getMallName(), LanguageType.LANGUAGE_DEFAULT));
            roleShopBuy.setItemNum(Integer.parseInt(count));
            roleShopBuy.setEvent("shopbuy");
            roleShopBuy.setCreatedTime((int) TimeHelper.getSysCurSeconds());
            LogAnalysisPushQueue.add(roleShopBuy);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    private static void buildPushHeartbeat(GamePlayer player) {
        HeartBeat heartBeat = new HeartBeat();
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        if (serverInfo == null) {
            log.error("Heartbeat-serverInfo no fount, serverId:{}", GameServer.getInstance().getServerId());
            return;
        }
        UserInfo userInfo = player.getUserInfo();
        heartBeat.setUser_id(userInfo.getOpenId());
        heartBeat.setRole_id(String.valueOf(userInfo.getUserId()));
        heartBeat.setRole_name(userInfo.getNickName());
        heartBeat.setRole_level(userInfo.getTitleId());
        heartBeat.setServer_id(String.valueOf(serverInfo.getServerId()));
        heartBeat.setServer_name(serverInfo.getServerName());
        heartBeat.setEvent("heartbeat");
        heartBeat.setRole_vip(0);//todo
        heartBeat.setDevice_id(player.getDeviceId());
        heartBeat.setClient_type(0);//todo
        heartBeat.setSource_id(String.valueOf(serverInfo.getChannelId()));//todo
        heartBeat.setEvent_ts((int) TimeHelper.getSysCurSeconds());
        PushQueue.add(heartBeat);
    }


}
